/**
 * Created by suweiming on 2018/12/4.
 */
$(function () {

    var config = {
        query: '/offer/query?statusPt=1&size=' + maxSize + '&',//分页查询URL,
    };
    var searchObj = parseSearch();
    var args = {
        theme: { // 主题

            init: function (searchObj) { //初始化方法
                var themeName = decodeURIComponent(searchObj.name);
                $('.btn-return').attr('href', './index.html?type=theme&pcId=' + (searchObj.pcId) + '&name=' + themeName + '')
                $('.title').html('设置"' + themeName + '"主题商品');
                if (!window.transferRightItems) {
                    $.get('/dataR/selectBy?type1=theme-shop&sourceId=' + searchObj.id, function (res) {
                        var list = _.pluck(res.list, 'targetId');
                        window.transferSelectedRightItems = list || [];
                        search({}, true);
                    });
                }
            },
            save: function () {
                var ids = [];
                $('.transfer-right tbody tr').each(function (index, item) {
                    var $json = $(item).data('json');
                    ids.push($json.id);
                });
                if (!ids.length) {
                    if (!confirm('您未为该主题设置任何商品，确认保存?')) {//
                        return;
                    }
                }
                $.post('/offer/addDataR', {
                    ids: ids.join(','),
                    type1: 'theme-shop',
                    sourceId: searchObj.id,
                }, function (res) {
                    if (res.code == 200) {
                        fnSuccess('保存成功～');
                    } else {
                        return alert(res.error || '保存失败！');
                    }
                })
            }
        },
        ups: { // 批量上架
            preInit: function () {
                config.query = '/offer/query?size=' + maxSize;
            },
            init: function (searchObj) { //初始化方法
                $('.btn-return').attr('href', '../../product/offer/index.html')
                $('.title').html('批量上架');
                if (!window.transferRightItems) {
                    $.get('/offer/query?status=1&size=' + maxSize, function (res) {

                        var list = _.pluck(res.list, 'id');
                        window.transferSelectedRightItems = list || [];
                        search({}, true);
                    });
                }
            },
            save: function () {
                var ids = [], down = [];
                $('.transfer-right tbody tr').each(function (index, item) {
                    var $json = $(item).data('json');
                    ids.push($json.id);
                });

                $('.transfer-left tbody tr').each(function (index, item) {
                    var $json = $(item).data('json');
                    down.push($json.id);
                });
                if (!ids.length) {
                    if (!confirm('您下架了所有商品，确认保存?')) {//
                        return;
                    }
                }
                //$.po
                $.post('/offer/ups', {
                    ids: ids.join(','),
                    downIds: down.join(','),
                }, function (res) {
                    if (res.code == 200) {
                        if (res.data && res.data.length) {
                            return alert('满足条件商品已经上架. ID为' + res.data.join(',') + '的商品，因不满足上架条件无法完成上架.')
                        }
                        fnSuccess('保存成功～');
                    } else {
                        if (res.data && res.data.size) {
                            return alert('ID为' + res.data.join(',') + '的商品，因不满足上架条件无法完成上架.')
                        }
                        return alert(res.error || '保存失败！');

                    }
                })
            }
        },
        groups: { // 批量上架
            preInit: function () {
                config.query = '/offer/query?size=' + maxSize;
            },
            init: function (searchObj) { //初始化方法
                $('.btn-return').attr('href', '../../product/offer/index.html')
                $('.title').html('批量设置拼团');
                if (!window.transferRightItems) {
                    $.get('/offer/query?statusPt=1&size=' + maxSize, function (res) {
                        var list = _.pluck(res.list, 'id');
                        window.transferSelectedRightItems = list || [];
                        search({}, true);
                    });
                }
            },
            save: function () {
                var ids = [], down = [];
                $('.transfer-right tbody tr').each(function (index, item) {
                    var $json = $(item).data('json');
                    ids.push($json.id);
                });

                $('.transfer-left tbody tr').each(function (index, item) {
                    var $json = $(item).data('json');
                    down.push($json.id);
                });
                if (!ids.length) {
                    if (!confirm('您撤下了所有拼团，确认保存?')) {//
                        return;
                    }
                }
                $.post('/offer/groups', {
                    ids: ids.join(','),
                    downIds: down.join(','),
                }, function (res) {
                    if (res.code == 200) {
                        fnSuccess('设置成功～');
                    } else {
                        return alert(res.error || '设置失败！');
                    }
                });
            }
        },
        discount: { // 折扣活动
            init: function () { //初始化方法
                var name = decodeURIComponent(searchObj.name);// 折扣
                $('.btn-return').attr('href', './index.html?type=' + searchObj.type)//
                $('.title').html('设置"' + name + '"折扣商品');
                if (!window.transferRightItems) {
                    $.get('/dataR/selectBy?type1=discount-offer&sourceId=' + searchObj.id, function (res) {
                        var list = _.pluck(res.list, 'targetId');
                        window.transferSelectedRightItems = list || [];
                        search({}, true);
                    });
                }
            },
            save: function () {
                var ids = [];
                $('.transfer-right tbody tr').each(function (index, item) {
                    var $json = $(item).data('json');
                    ids.push($json.id);
                });
                if (!ids.length) {
                    if (!confirm('您没有为该折扣设置任何商品，确认保存?')) {//
                        return;
                    }
                }
                $.post('/offer/addDataR', {
                    ids: ids.join(','),
                    type1: 'discount-offer',
                    sourceId: searchObj.id,
                }, function (res) {
                    if (res.code == 200) {
                        fnSuccess('保存成功～');
                    } else {
                        return alert(res.error || '保存失败！');
                    }
                })
            }
        }
    };

    var arg = args[searchObj.type1 || 'theme'];
    if (arg.preInit) {
        arg.preInit();
    }
    var query = {};
    selectGoods({
        url: '/category/list?type1=brand&',
        name: 'brand',
        key: '请选择品牌搜索',
        placeholder: '请选择品牌搜索'
    })
    selectGoods({
        url: '/category/list?type1=shop-category&',
        name: 'categoryId',
        key: '请选择分类搜索',
        placeholder: '请选择分类搜索'
    })

    onClick($('.search-btn'), function () {
        var opt = {};
        if ($('[name=categoryId]').val()) {
            opt.categoryId = $('[name=categoryId]').val();
        }
        if ($('[name=brand]').val()) {
            opt.brand = $('[name=brand]').val();
        }
        if ($('[name=name]').val()) {
            opt.name = $('[name=name]').val();
        }
        search(opt, true)
    });
    var $left = $('.fn-btn.icon-chevron-left');
    var $lefts = $('.fn-btn.icon-chevrons-left');

    /**
     * 初始化右侧穿梭框
     * @param list
     */
    function generateTrasferRight(list) {
        list = uniqueFn(list);
        window.transferRightItems = list;
        var _$table = $('.transfer-right .table-responsive .table');
        _$table.$table($.extend(TABLE_SETTING, {
            checkbox: false, // 是否显示复选框
            seqNum: false, // 是否显示序号
            createBtn: function () {
                enableBtn($right, {});
                enableBtn($right, {});
                disableBtn($left, {});
            },
            destroyBtn: function () {
                disableBtn($rights, {});
                disableBtn($right, {});
            },
            rendered: function () {
                if (list.length == 0) {
                    _$table.find('tbody').html('<tr><td>没有符合条件的商品</td></tr>');
                }
                onClick($left.closest('.btn'), function () {//
                    var $active = $('.transfer-right .active');
                    if (!$active.length) return fnSuccess('请选择右侧商品');
                    var $json = $active.data('json');
                    window.transferLeftItems = window.transferLeftItems || [];
                    window.transferLeftItems.push($json);
                    window.transferRightItems = _.filter(window.transferRightItems, function (item) {
                        return item.id != $json.id;
                    });
                    $active.remove();
                    generateTrasferLeft(window.transferLeftItems);
                });
                onClick($lefts.closest('.btn'), function () {//
                    var $active = $('.transfer-right tbody'), items = [];
                    if (!$active.find('tr').length) {
                        return fnSuccess('没有更多可选项');
                    }
                    window.transferLeftItems = list;
                    window.transferLeftItems = window.transferLeftItems || [];
                    window.transferLeftItems = window.transferLeftItems.concat(window.transferRightItems);
                    window.transferRightItems = [];//
                    $active.html('');
                    generateTrasferLeft(window.transferLeftItems)
                });
            },
            fields: [
                {
                    name: 'thumbnail', label: '缩略图',
                    filter: function (item) {
                        if (item.thumbnail) {
                            return '<a target="_blank" href="' + item.thumbnail + '" title="点击预览"><img style="height:60px;border-radius:5px;" src="' + item.thumbnail + '" /></a>'
                        } else {
                            return '<a  href="javascript:void(0);" title="点击预览"><img style="height:60px;border-radius:5px;" src="/admin/imgs/upload/default-img.png" /></a>'
                        }
                    }
                },
                {name: 'name', label: '商品名称', enableSearch: true},
            ],
            data: list || [],
        }));
    }

    var $right = $('.fn-btn.icon-chevron-right');
    var $rights = $('.fn-btn.icon-chevrons-right');

    function uniqueFn(list) {
        list = _.uniq(list, function (item) {
            return item.id;
        });
        return list;
    }

    /**
     * 初始化左侧穿梭框
     * @param list
     */
    function generateTrasferLeft(list) {
        var _$table = $('.transfer-left .table-responsive .table');
        if (window.transferSelectedRightItems) { //初始化
            window.transferRightItems = _.filter(list, function (item) {
                return window.transferSelectedRightItems.indexOf(item.id) > -1;
            })
            list = _.filter(list, function (item) {
                return window.transferSelectedRightItems.indexOf(item.id) == -1;
            });
            window.transferSelectedRightItems = false;
            generateTrasferRight(window.transferRightItems);//初始化右侧内容
        }

        list = uniqueFn(list);
        list = _.filter(list, function (item) {
            var first = _.find(window.transferRightItems, function (ite) { // 查找第一个元素
                return (ite.id == item.id)
            });
            return !first;//
        });
        window.transferLeftItems = list;
        _$table.$table($.extend(TABLE_SETTING, {
            checkbox: false, // 是否显示复选框
            seqNum: false, // 是否显示序号
            sort: search, //排序回调函数
            toolbar: '.toolbar',
            enableSetting: true,//允许自定义显示列
            createBtn: function () {
                enableBtn($left, {});
                enableBtn($lefts, {});
                disableBtn($right, {});
            },
            destroyBtn: function () {
                disableBtn($lefts, {});
                disableBtn($left, {});
            },
            search: function (obj) { //搜索框查询函数
                search(obj)
            },
            rendered: function () {
                if (list.length == 0) {
                    _$table.find('tbody').html('<tr><td>没有符合条件的商品</td></tr>');
                }
                onClick($right.closest('.btn'), function () {//
                    var $active = $('.transfer-left .active');
                    if (!$active.length) return fnSuccess('请选择左侧商品');
                    var $json = $active.data('json');

                    window.transferRightItems = window.transferRightItems || [];
                    window.transferRightItems.push($json);
                    window.transferLeftItems = _.filter(window.transferLeftItems, function (item) {
                        return item.id != $json.id;
                    });
                    $active.remove();
                    generateTrasferRight(window.transferRightItems);
                })
                onClick($rights.closest('.btn'), function () {//
                    var $active = $('.transfer-left tbody'), items = [];
                    if (!$active.find('tr').length) {
                        return fnSuccess('没有更多可选项');
                    }
                    window.transferLeftItems = list;
                    window.transferRightItems = window.transferRightItems || [];
                    window.transferRightItems = window.transferRightItems.concat(window.transferLeftItems);
                    window.transferLeftItems = [];//
                    $active.html('');
                    generateTrasferRight(window.transferRightItems)
                })
            },
            fields: [
                {
                    name: 'thumbnail', label: '缩略图',
                    filter: function (item) {
                        if (item.thumbnail) {
                            return '<a target="_blank" href="' + item.thumbnail + '" title="点击预览"><img style="height:60px;border-radius:5px;" src="' + item.thumbnail + '" /></a>'
                        } else {
                            return '<a  href="javascript:void(0);" title="点击预览"><img style="height:60px;border-radius:5px;" src="/admin/imgs/upload/default-img.png" /></a>'
                        }
                    }
                },
                {name: 'name', label: '商品名称', enableSearch: true},
            ],
            data: list || [],
        }));
    }

    /**
     * 保存按钮
     */
    onClick($('.btn-save'), function () {
        arg.save()
    })
    /**
     * 查询
     * @param obj
     * @param isForce
     */
    function search(obj, isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        $.get(config.query + ajaxArgStrGenerator(obj || {}), function (res) {
            return generateTrasferLeft(res.list);
        });
    }


    if (arg.init) {
        arg.init(searchObj);
    }


});